import { useCrudForm } from "@/composables/useCrudForm";
import { visitorFormConfig } from "../form-config";
import SysvisitorrecordrequestbillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysVisitorRecordRequestBill,
  ISysVisitorRecordRequestBillVm,
} from "../api/interface";

/**
 * 访客信息专用 Composable
 */
export function useVisitorInfo() {
  // 创建API实例
  const api = SysvisitorrecordrequestbillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    visitorReason: async () => {
      const commonApiInstance = commonApi();
      return await commonApiInstance.GetSysVisitorReasons();
    },
    group: async () => {
      const commonApiInstance = commonApi();
      return await commonApiInstance.GetSysGroups();
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysVisitorRecordRequestBill, ISysVisitorRecordRequestBillVm>(
    visitorFormConfig,
    apiConfig,
    optionLoaders
  );

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysVisitorRecordRequestBillVm => {
    return {
      Entity: {
        VisitorReasonId: crudForm.pickerValues.visitorReason || null,
        Name: crudForm.formData.name || null,
        Phone: crudForm.formData.phone || null,
        IdCardNo: crudForm.formData.idCardNo || null,
        IdCardFrontPhotoId: crudForm.formData.idCardFrontPhoto || null,
        IdCardBackPhotoId: crudForm.formData.idCardBackPhoto || null,
        Company: crudForm.formData.company || null,
        CarNo: crudForm.formData.carNo || null,
        UserId: null,
        ReservationTime: crudForm.formatDateTime(crudForm.formData.reservationTime),
        Receptionist: crudForm.formData.receptionist || null,
        ReceptionistPhone: crudForm.formData.receptionistPhone || null,
        RejectReason: crudForm.formData.rejectReason || "",
        EntryTime: crudForm.formatDateTime(crudForm.formData.entryTime),
        LeaveTime: crudForm.formatDateTime(crudForm.formData.leaveTime),
        Approver: crudForm.formData.approver || "",
        ApprovalTime: crudForm.formData.approvalTime || "",
        GroupId: crudForm.pickerValues.group || null,
        BillCode: crudForm.formData.billCode || null,
        BillStatus: "草稿",
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
      },
      ActionName: null,
      IsMyApprove: null,
    };
  };

  /**
   * 统一的数据映射函数
   * @param status "draft" | "submit" - 操作类型
   */
  const buildEntityData = (status: "draft" | "submit"): ISysVisitorRecordRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    // 获取原始状态值
    const originalBillStatus = originalData.BillStatus;
    const originalWorkflowStatus = originalData.WorkflowStatus;

    // 根据模式设置状态
    let billStatus, workflowStatus;

    if (status === "draft") {
      // draft模式：保持原有状态
      billStatus = originalBillStatus;
      workflowStatus = originalWorkflowStatus;
    } else {
      // submit模式：BillStatus保持原状态，WorkflowStatus条件判断
      billStatus = originalBillStatus;
      workflowStatus = originalWorkflowStatus === "待提交" ? "提交中" : originalWorkflowStatus;
    }

    return {
      Entity: {
        ID: originalData.ID || null,
        VisitorReasonId: crudForm.pickerValues.visitorReason || originalData.VisitorReasonId,
        Name: crudForm.formData.name || originalData.Name,
        Phone: crudForm.formData.phone || originalData.Phone,
        IdCardNo: crudForm.formData.idCardNo || originalData.IdCardNo,
        IdCardFrontPhotoId: crudForm.formData.idCardFrontPhoto || originalData.IdCardFrontPhotoId,
        IdCardBackPhotoId: crudForm.formData.idCardBackPhoto || originalData.IdCardBackPhotoId,
        Company: crudForm.formData.company || originalData.Company,
        CarNo: crudForm.formData.carNo || originalData.CarNo,
        UserId: originalData.UserId || null,
        ReservationTime: crudForm.formatDateTime(crudForm.formData.reservationTime) || originalData.ReservationTime,
        Receptionist: crudForm.formData.receptionist || originalData.Receptionist,
        ReceptionistPhone: crudForm.formData.receptionistPhone || originalData.ReceptionistPhone,
        RejectReason: crudForm.formData.rejectReason || originalData.RejectReason || "",
        EntryTime: crudForm.formatDateTime(crudForm.formData.entryTime) || originalData.EntryTime,
        LeaveTime: crudForm.formatDateTime(crudForm.formData.leaveTime) || originalData.LeaveTime,
        Approver: crudForm.formData.approver || originalData.Approver || "",
        ApprovalTime: crudForm.formData.approvalTime || originalData.ApprovalTime || "",
        GroupId: crudForm.pickerValues.group || originalData.GroupId,
        BillCode: originalData.BillCode || crudForm.formData.billCode || null,
        BillStatus: billStatus,
        WorkflowStatus: workflowStatus,
        Remark: crudForm.formData.remark || originalData.Remark,
      },
      ActionName: null,
      IsMyApprove: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑保存）- 保持向后兼容
   */
  const convertFormDataToApiFormatForEdit = (): ISysVisitorRecordRequestBillVm => {
    return buildEntityData("draft");
  };

  /**
   * 转换表单数据为API格式（编辑提交）- 保持向后兼容
   */
  const convertFormDataToApiFormatForSubmit = (): ISysVisitorRecordRequestBillVm => {
    return buildEntityData("submit");
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 访客基本信息
    name: "Name",
    phone: "Phone",
    idCardNo: "IdCardNo",
    company: "Company",
    carNo: "CarNo",

    // 身份信息
    idCardFrontPhoto: "IdCardFrontPhotoId",
    idCardBackPhoto: "IdCardBackPhotoId",

    // 预约信息
    visitorReason: "VisitorReasonId", // 直接使用ID，让选择器处理逻辑来转换
    reservationTime: "ReservationTime",
    receptionist: "Receptionist",
    receptionistPhone: "ReceptionistPhone",
    group: "GroupId", // 直接使用ID，让选择器处理逻辑来转换

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
    rejectReason: "RejectReason",

    // 访客出入信息
    entryTime: "EntryTime",
    leaveTime: "LeaveTime",
  };

  /**
   * 加载访客详情数据
   */
  const loadVisitorDetail = async (id: string): Promise<boolean> => {
    const detail = await crudForm.getDetail(id);

    if (detail) {
      // 检查原始数据中的日期字段
      const dateFields = ["ReservationTime", "ApprovalTime", "EntryTime", "LeaveTime"];
      dateFields.forEach(field => {
        if ((detail as any)[field]) {
          console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
        }
      });

      // 先使用通用转换
      crudForm.convertApiDataToFormData(detail, fieldMapping);

      // 检查转换后的日期字段（如需要可以在这里添加日期字段的特殊处理）

      // 添加特殊处理，确保选择器字段正确映射
      await ensurePickerFieldsMapping(detail);

      return true;
    }
    return false;
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理访客事由
    if (apiData.VisitorReasonId && visitorFormConfig.visitorReason?.optionsData) {
      const reasonOption = visitorFormConfig.visitorReason.optionsData.find(
        (item: any) => item.value === apiData.VisitorReasonId
      );
      if (reasonOption) {
        crudForm.formData.visitorReason = reasonOption.text;
        crudForm.pickerValues.visitorReason = reasonOption.value;
      }
    }

    // 处理部门
    if (apiData.GroupId && visitorFormConfig.group?.optionsData) {
      const groupOption = visitorFormConfig.group.optionsData.find(
        (item: any) => item.value === apiData.GroupId
      );
      if (groupOption) {
        crudForm.formData.group = groupOption.text;
        crudForm.pickerValues.group = groupOption.value;
      }
    }
  };

  /**
   * 创建访客记录
   */
  const createVisitor = async (): Promise<{
    success: boolean;
    data?: ISysVisitorRecordRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForCreate();
    const result = await crudForm.create(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 统一的保存/提交处理函数
   * @param type "save" | "submit" - 操作类型
   */
  const processFormData = async (
    type: "save" | "submit"
  ): Promise<{
    success: boolean;
    data?: ISysVisitorRecordRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    // 构建数据
    const apiData = buildEntityData(type === "submit" ? "submit" : "draft");

    console.log(`${type === "submit" ? "提交" : "保存"}数据:`, apiData);

    const result = await crudForm.update(apiData);

    // 更新本地状态
    if (type === "submit" && result) {
      // 根据新的状态逻辑更新本地状态
      const originalWorkflowStatus = crudForm.originalData.value?.WorkflowStatus;
      if (originalWorkflowStatus === "待提交") {
        // 更新原始数据中的WorkflowStatus
        if (crudForm.originalData.value) {
          crudForm.originalData.value.WorkflowStatus = "提交中";
        }
      }
      // BillStatus保持不变
    }

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 保存访客记录（编辑）- 使用统一的处理函数
   */
  const saveVisitor = async (): Promise<{
    success: boolean;
    data?: ISysVisitorRecordRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    return await processFormData("save");
  };

  /**
   * 提交访客记录（编辑）- 使用统一的处理函数
   */
  const submitVisitor = async (): Promise<{
    success: boolean;
    data?: ISysVisitorRecordRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
  }> => {
    return await processFormData("submit");
  };

  /**
   * 初始化单据编号
   */
  const initializeBillCode = async (): Promise<void> => {
    const billCode = await crudForm.getBillCode();
    if (billCode) {
      crudForm.formData.billCode = billCode;
    }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 访客信息专用方法
    loadVisitorDetail,
    createVisitor,
    saveVisitor,
    submitVisitor,
    initializeBillCode,

    // 统一处理函数
    processFormData,
    buildEntityData,

    // API数据转换方法（保持向后兼容）
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,
    convertFormDataToApiFormatForSubmit,

    // 字段映射
    fieldMapping,
  };
}
